﻿using App.Authorization.Roles;
using App.Authorization.Users;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace App.EntityFramework.Seed
{
    public class HostRoleAndUserCreator
    {
        private readonly WebPlusDbContext _context;

        public HostRoleAndUserCreator(WebPlusDbContext context)
        {
            _context = context;
        }

        public void Create()
        {
            CreateHostRoleAndUsers();
        }

        private void CreateHostRoleAndUsers()
        {
            //Admin role for host
            var adminRoleForHost = _context.Role.FirstOrDefault(r => r.TenantId == null && r.RoleName == Role.HostDefaultRoleName);

            if (adminRoleForHost == null)
            {
                adminRoleForHost = _context.Role.Add(new Role() { RoleName= Role.HostDefaultRoleName, RoleDesc= Role.HostDefaultRoleName, TenantId=null });
                _context.SaveChanges();
            }

            //admin user for host
            var adminUserForHost = _context.User.FirstOrDefault(u => u.TenantId == null && u.UserName == User.DefaultUserName);
            if (adminUserForHost == null)
            {
                adminUserForHost = _context.User.Add(
                    new User
                    {
                        TenantId = null,
                        UserName = User.DefaultUserName,
                        Email = "admin@webplus.org.cn",
                        EmailConfirmed = true,
                        IsActive = true,
                        PasswordHash = "1000:XagbFPKkV97cOsEmHIP9nffok3US64A8:+05tjUFHcQHdpE088kGm27HoCoZRpf3W" //123456
                    });
                _context.SaveChanges();

                //Assign Admin role to admin user
                _context.UserRole.Add(new UserRole(null, adminUserForHost.Id, adminRoleForHost.Id));
                _context.SaveChanges();

                //Grant all permissions
                var allPermissions = _context.MenuPermission.ToList();

                foreach (var permission in allPermissions)
                {
                    _context.Permission.Add(
                        new RolePermission
                        {
                            TenantId = null,
                            MenuId = permission.Id,
                            IsGranted = true,
                            RoleId = adminRoleForHost.Id
                        });
                }

                _context.SaveChanges();
            }
        }
    }
}
